package edu.cuit.svsp.service.impl;

import edu.cuit.svsp.mapper.UserMapper;
import edu.cuit.svsp.service.UserService;
import edu.cuit.svsp.util.MD5Util;
import edu.cuit.svsp.vo.UserLoginVo;
import edu.cuit.svsp.entity.User;
import edu.cuit.svsp.exception.AccountOrPasswordErrorException;
import edu.cuit.svsp.vo.UserSearchVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @className: UserServiceImpl
 * @author: pjy
 * @description: 用户Service实现类
 * @date: 2024/7/2
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    //登录
    @Override
    public User login(UserLoginVo vo) {
        User user = userMapper.findByAccount(vo.getAccount());
        //用户不存在或密码错误
        if (user == null || !user.getPassword().equals(MD5Util.encryptMD5(vo.getPassword()))) {
            throw new AccountOrPasswordErrorException("账号或密码错误");
        }
        return user;
    }

    @Override
    public List<User> search(UserSearchVo vo) {
        if (vo.getLevel().equals("all") && vo.getState().equals("all")) {
            return userMapper.findAll(vo.getName());
        } else if (vo.getLevel().equals("all") && !vo.getState().equals("all")) {
            return userMapper.findByState(vo.getState(), vo.getName());
        } else if (!vo.getLevel().equals("all") && vo.getState().equals("all")) {
            return userMapper.findByLevel(vo.getLevel(), vo.getName());
        } else {
            return userMapper.findByLevelAndState(vo.getLevel(), vo.getState(), vo.getName());
        }
    }

    @Override
    public boolean lock(Integer id) {
        return userMapper.lock(id);
    }

    @Override
    public boolean pass(Integer id) {
        return userMapper.pass(id);
    }

    @Override
    public boolean updateLevel(Integer id, String level) {
        return userMapper.updateLevel(id, level);
    }

    @Override
    public boolean updatePassword(int id, String oldPassword, String newPassword) {
        boolean flag = userMapper.isPassword(id, MD5Util.encryptMD5(oldPassword));
        System.out.println(flag);
        if (!flag) {
            return false;
        } else {
            return userMapper.updatePassword(id, MD5Util.encryptMD5(newPassword));
        }
    }

    @Override
    public boolean updateAvatar(String avatarUrl,Integer id) {
        return userMapper.updateAvatar(avatarUrl,id);
    }

    @Override
    public User findById(int uid) {
        return userMapper.findById(uid);
    }
}
